<?php
/**
 * 微店优惠券类
 * @author 志杨
 *
 */
class Coupons{
    var $db;
    
    function __construct(){
        global $db;
        
        $this -> db     = & $db;
    }
    
    /**
     * 添加或编辑优惠券礼包配置
     * @param unknown $data
     */
    public function add_edit_package_config($data){
        if(!empty($data)){
            if(isset($data['id']) && $data['id']>0){//编辑
                $sql = "select * from ".MICROSHOPCOUPONSCONFIG." where id={$data['id']}";
                $this->db->query($sql);
                $configInfo = $this->db->fetchRow();
                if(empty($configInfo)){
                    return false;
                }
                
                $sql = "update ".MICROSHOPCOUPONSCONFIG." set name='{$data['name']}',config_json='{$data['config_json']}',status='{$data['status']}' where id={$data['id']}";
                $this->db->query($sql);
                
                return true;
            }else{//新增
                $sql = "insert into ".MICROSHOPCOUPONSCONFIG." (`name`,`config_json`,`status`,`create_user`) values('{$data['name']}','{$data['config_json']}','{$data['status']}','{$_SESSION['ADMIN_USER']}')";
                $this->db->query($sql);
                
                return true;
            }
        }
        
        return false;
    }
    
    /**
     * 为用户生成一个优惠券礼包
     * @param unknown $memberId
     * @param unknown $configId 礼包配置ID
     */
    public function createOnePackage($memberId,$configId){
        if($configId>0){
            $sql = "select * from ".MICROSHOPCOUPONSCONFIG." where id={$configId}";
            $this->db->query($sql);
            $configInfo = $this->db->fetchRow();
            if(empty($configInfo)){
                return false;
            }
            
            //优惠券信息
            $couponsInfo = json_decode($configInfo['config_json'],true);
            //先写入一个礼包
            $sql = "insert into ".MICROSHOPCOUPONSPACKAGE." (`member_id`,`package_name`,`create_user`) values('{$memberId}','{$configInfo['name']}','{$_SESSION['ADMIN_USER']}')";
            $this->db->query($sql);
            $packageId = $this->db->lastid();
            
            
            if($packageId>0){
                //生成优惠券
                foreach ($couponsInfo as $val)
                {
                    $val['title'] = $configInfo['name']."中".$val['cpns_then']."券";
                    for($i=0;$i<$val['cpns_num'];$i++){
                        //获取优惠券编号
                        $cpns_key = $this->createCpnsKey();
                        //写入优惠券表
                        $this->insertOneCoupons($memberId, $packageId, $cpns_key, $val);
                    }
                }
                
                return true;
            }
            
            return false;
        }
        
        return false;
    }
    
    /**
     * 生成一张优惠券的编号
     * @param number $length
     */
    public function createCpnsKey($length=10){
        $codePre = "W";
        $codeArr = array();
        for ($i = 0; $i < ($length-1); $i ++) {
            $type = mt_rand(1,2);
            if($type==1){//字母
                while (true) {
                    $ascii = mt_rand(65, 90);
                    if ($ascii != 79 && $ascii != 73) {
                        // 排除O字母和I
                        break;
                    }
                }
                $codeArr[] = chr($ascii);
            }else{//数字
                $num = mt_rand(2,9);
                $codeArr[] = $num;
            }
        }
        $code = implode('', $codeArr);
        $code = $codePre.$code;
        
        $sql = "select id from ".MICROSHOPCOUPONS." where cpns_key='{$code}' limit 1";
        $this->db->query($sql);
        $existsData = $this->db->fetchRow();
        if (! empty($existsData)) {
            // 重复了，则递归生成
            return $this->createCpnsKey();
        }
        
        return $code;
    }
    
    /**
     * 写入一张优惠券
     * @param unknown $memberId
     * @param unknown $couponsInfo
     */
    private function insertOneCoupons($memberId,$packageId,$cpns_key,$couponsInfo){
        if(!($memberId>0) || !($packageId>0) || empty($cpns_key)){
            return false;
        }
        
        $start_time = date('Y-m-d H:i:s');
        $end_time = date('Y-m-d H:i:s',strtotime("+".intval($couponsInfo['overtime'])." day"));
        if($end_time>'2038-01-18 23:59:59'){
            $end_time = '2038-01-18 23:59:59';
        }
        
        $sql = "insert into ".MICROSHOPCOUPONS." (`title`,`package_id`,`member_id`,`cpns_key`,`cpns_if`,`cpns_then`,`start_time`,`end_time`) values('{$couponsInfo['title']}','{$packageId}','{$memberId}','{$cpns_key}','{$couponsInfo['cpns_if']}','{$couponsInfo['cpns_then']}','{$start_time}','{$end_time}')";
        $this->db->query($sql);
        
        return true;
    }
    
    /**
     * 更改优惠券状态
     * @param unknown $couponsId
     * @param unknown $status
     */
    public function updateCouponsStatus($couponsId,$status){
        if(!empty($couponsId)){
            $couponsId = str_replace('，', ',', trim($couponsId));
            $sql = "update ".MICROSHOPCOUPONS." set status='{$status}' where id in({$couponsId})";
            $this->db->query($sql);
            
            return true;
        }
        
        return false;
    }
}
?>